package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDTO dto) {
        //1.判断用户名密码不能为空
        if(StringUtils.isBlank(dto.getPassword())||StringUtils.isBlank(dto.getName())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或密码为空");
        }
        //2.根据用户名查用户
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        //判断用户是否存在
        if(wmUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //判断密码是否正确
        //获得用户输入的密码
        String asHex = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        if(!wmUser.getPassword().equals(asHex)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码不正确");
        }
        //3.判断状态是否为9
        if(wmUser.getStatus().intValue()!= AdminConstants.PASS_AUTH){
            //状态异常
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常，请联系管理员");
        }
        //修改登录时间
        wmUser.setLoginTime(new Date());
        this.updateById(wmUser);
        //颁发JWTtoken
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        //将wmUser 、token信息返回
        Map map = new HashMap<>();
        map.put("token",token);
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser,wmUserVO);
        map.put("user",wmUserVO);
        return ResponseResult.okResult(map );
    }
}
